﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	public class DimEquipmentManage
	{
		public DimEquipmentManage(ExternalCommandData command, DimEquipmentData eData, bool bIs)
		{
			this.commandData = command;
			this.doc = this.commandData.Application.ActiveUIDocument.Document;
			this.equipmentData = eData;
			this.IsPlan = bIs;
			UserSetting userSetting = new UserSetting();
			this.fontSetting = userSetting.GetFontSetting();
		}

		public bool Run()
		{
			bool result;
			using (DimEquipmentJig dimEquipmentJig = new DimEquipmentJig(this.commandData.Application.ActiveUIDocument, this.equipmentData))
			{
				if (dimEquipmentJig.SelEquipment() && dimEquipmentJig.DimPoint())
				{
					result = this.LayDim(dimEquipmentJig.refEpui, dimEquipmentJig.PointDim);
				}
				else
				{
					result = false;
				}
			}
			return result;
		}

		private bool LayDim(Reference refEqui, XYZ dimPoint)
		{
			string fsName = "标准";
			FamilyInstance familyInstance = this.doc.GetElement(refEqui.ElementId) as FamilyInstance;
			if (familyInstance == null)
			{
				return false;
			}
			ElementSet entList = new ElementSet();
			Transaction transaction = null;
			try
			{
				transaction = new Transaction(this.doc, "设备标注");
				transaction.Start();
				if (this.equipmentData.DimStype == 1)
				{
					bool isCustomNumber = this.equipmentData.NumberType == 2;
					if (!this.SetDimEquipmentParameters(this.commandData.Application, familyInstance, this.equipmentData.NumberContent, isCustomNumber))
					{
						YJKMessageBox.Show("设备没有连接，请使用“其它设备”选项来标注！");
						transaction.RollBack();
						return true;
					}
				}
				else
				{
					this.SetDimEquipmentParameters(familyInstance, this.equipmentData.DimContent);
				}
				string text = "";
				FamilySymbol markTagSymbolByName = YJKRevitTools.GetMarkTagSymbolByName("MarkTag", "HY_设备标注", fsName, this.doc, ref text, BuiltInCategory.OST_MechanicalEquipmentTags);
				if (markTagSymbolByName == null)
				{
					transaction.RollBack();
					return false;
				}
				XYZ globalPoint = refEqui.GlobalPoint;
				if (this.IsPlan)
				{
					string text2 = "";
					Parameter parameter = familyInstance.GetParameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
					if (parameter != null)
					{
						text2 = parameter.AsString();
					}
					double num = dimPoint.Z;
					num = this.doc.ActiveView.GenLevel.Elevation;
					XYZ xyz = new XYZ(globalPoint.X, globalPoint.Y, num);
					XYZ xyz2 = XYZ.BasisY;
					XYZ xyz3 = XYZ.BasisX;
					if (dimPoint.X < globalPoint.X)
					{
						xyz3 = -1.0 * XYZ.BasisX;
					}
					MarkOperation markOperation = new MarkOperation();
					double num2 = 1.0;
					double num3 = 1.0;
					markOperation.GetTagTextWidthAndHeight(text2, this.doc, ref num2, ref num3);
					if (RevitVersion.GetVersionNumber(this.doc) == "2015" || RevitVersion.GetVersionNumber(this.doc) == "2014")
					{
						CommonFont commonFont = new UserSetting().GetFontSetting();
						num2 = (double)text2.Length * num3 * commonFont.FontGWRotia * 0.36;
					}
					xyz2 *= num3 / 609.6 + this.fontSetting.LeadDistance / 304.8;
					xyz3 *= num2 * this.fontSetting.LeadRotia / 304.8;
					XYZ xyz4 = new XYZ(dimPoint.X, dimPoint.Y, num);
					XYZ xyz5 = new XYZ(xyz4.X, xyz4.Y, xyz4.Z);
					if (this.equipmentData.IsLead)
					{
						xyz5 += xyz3 / 2.0 + xyz2;
					}
					IndependentTag independentTag = RevitVersionFuncs.NewTag(this.doc, this.doc.ActiveView, new Reference(familyInstance), false, 0, 0, xyz5);
					independentTag.ChangeTypeId(markTagSymbolByName.Id);
					independentTag.TagHeadPosition = xyz5;
					AssociationMarkInfo.WriteMarkInfoToElement(independentTag, MarkType.Equipment);
					if (this.equipmentData.IsLead)
					{
						xyz5 = xyz4 + xyz3;
						Line item = Line.CreateBound(xyz, xyz4);
						Line item2 = Line.CreateBound(xyz4, xyz5);
						entList = this.CreateTagLines(new List<Line>
						{
							item,
							item2
						});
					}
				}
				else
				{
					IndependentTag independentTag2 = RevitVersionFuncs.NewTag(this.doc, this.doc.ActiveView, new Reference(familyInstance), false, 0, 0, dimPoint);
					independentTag2.ChangeTypeId(markTagSymbolByName.Id);
					independentTag2.TagHeadPosition = dimPoint;
					AssociationMarkInfo.WriteMarkInfoToElement(independentTag2, MarkType.Equipment);
				}
				transaction.Commit();
			}
			catch
			{
			}
			finally
			{
				if (transaction != null && (int)transaction.GetStatus() == 1)
				{
					transaction.RollBack();
				}
			}
			if (this.equipmentData.IsLead)
			{
				try
				{
					transaction = new Transaction(this.doc, "new Group");
					transaction.Start();
					this.CerateTagLinesGroup(entList);
					transaction.Commit();
				}
				catch
				{
				}
				finally
				{
					if (transaction != null && (int)transaction.GetStatus() == 1)
					{
						transaction.RollBack();
					}
				}
			}
			return true;
		}

		private double ScalingFactor()
		{
			try
			{
				return (double)this.doc.ActiveView.Scale / 100.0;
			}
			catch
			{
			}
			return 1.0;
		}

		private ElementSet CreateTagLines(List<Line> tagLines)
		{
			ElementSet elementSet = new ElementSet();
			for (int i = 0; i < tagLines.Count; i++)
			{
				DetailCurve detailCurve = this.doc.CreatYJKDetailCurve(tagLines.ElementAt(i));
				elementSet.Insert(detailCurve);
				int num = 0;
				while (i < RevitVersionFuncs.LineStyles(this.doc, detailCurve).Size)
				{
					GraphicsStyle graphicsStyle = RevitVersionFuncs.LineStyles(this.doc, detailCurve).get_Item(num) as GraphicsStyle;
					int hashCode = -2000042.GetHashCode();
					if (graphicsStyle.GraphicsStyleCategory.GetHashCode() == hashCode)
					{
						detailCurve.LineStyle = graphicsStyle;
						break;
					}
					num++;
				}
			}
			return elementSet;
		}

		private void CerateTagLinesGroup(ElementSet entList)
		{
			if (entList.Size < 1)
			{
				return;
			}
			AssociationMarkInfo.WriteMarkInfoToElement(RevitVersionFuncs.NewGroup(this.doc, entList), MarkType.Equipment);
		}

		private string GetSystemShort(FamilyInstance selEqui)
		{
			string result;
			try
			{
				Parameter parameter = selEqui.GetParameter(BuiltInParameter.RBS_SYSTEM_NAME_PARAM);
				if (parameter == null)
				{
					result = "";
				}
				else
				{
					string text = parameter.AsString();
					if (string.IsNullOrEmpty(text))
					{
						result = "";
					}
					else
					{
						text = text.Trim();
						int num = text.IndexOf(" ");
						if (num > 0 && num < text.Length)
						{
							text = text.Substring(0, num);
						}
						result = text;
					}
				}
			}
			catch
			{
				result = "";
			}
			return result;
		}

		public List<MechanicalSystemType> GetAllMechanicalSystemType(Autodesk.Revit.DB.Document doc)
		{
			List<MechanicalSystemType> list = new List<MechanicalSystemType>();
			foreach (Element element in new FilteredElementCollector(doc).OfClass(typeof(MechanicalSystemType)).ToElements())
			{
				MechanicalSystemType item = element as MechanicalSystemType;
				list.Add(item);
			}
			return list;
		}

		public bool SetDimEquipmentParameters(UIApplication uiApp, FamilyInstance selEqui, string number, bool isCustomNumber)
		{
			bool result = false;
			try
			{
				string systemShort = this.GetSystemShort(selEqui);
				string shareFilePath = Path.Combine(Product.DataLocation, "HYShared Parameters.txt");
				DefinitionFile defineFile = YJKRevitTools.OpenShareParamFile(uiApp, shareFilePath);
				CategorySet bdcategorySet = YJKRevitTools.GetBDCategorySet(uiApp, BuiltInCategory.OST_DuctSystem);
				TypeBinding elemBinding = YJKRevitTools.CreatElemBinding(uiApp, bdcategorySet, "type") as TypeBinding;
				YJKRevitTools.SetShareParameter(uiApp, defineFile, "管道参数", new List<string>
				{
					"设备标注编号"
				}, elemBinding, (BuiltInParameterGroup)(-5000123));
				List<MechanicalSystemType> allMechanicalSystemType = this.GetAllMechanicalSystemType(uiApp.ActiveUIDocument.Document);
				if (allMechanicalSystemType != null && allMechanicalSystemType.Count > 0 && selEqui != null)
				{
					Parameter parameter = selEqui.get_Parameter(BuiltInParameter.RBS_PIPING_SYSTEM_TYPE_PARAM);
					if (parameter != null)
					{
						foreach (MechanicalSystemType mechanicalSystemType in allMechanicalSystemType)
						{
							if (parameter.AsElementId() == mechanicalSystemType.Id)
							{
								int num = 0;
								Parameter parameter2 = mechanicalSystemType.GetParameter("设备标注编号");
								if (parameter2 != null)
								{
									num = Convert.ToInt32(parameter2.AsString());
								}
								Parameter parameter3 = selEqui.GetParameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
								if (parameter3 != null)
								{
									if (isCustomNumber)
									{
										parameter3.Set(this.equipmentData.DimFGText(systemShort, number));
										if (Convert.ToInt32(number) > num)
										{
											num = Convert.ToInt32(number) + 1;
										}
									}
									else
									{
										num++;
										parameter3.Set(this.equipmentData.DimFGText(systemShort, num.ToString()));
									}
								}
								if (parameter2 != null)
								{
									parameter2.Set(num.ToString());
								}
								result = true;
								break;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				ex.ToString();
				throw ex;
			}
			return result;
		}

		public bool SetDimEquipmentParameters(FamilyInstance selEqui, string number)
		{
			bool result;
			try
			{
				Parameter parameter = selEqui.GetParameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
				if (parameter != null)
				{
					parameter.Set(number);
				}
				result = true;
			}
			catch (Exception ex)
			{
				ex.ToString();
				result = false;
			}
			return result;
		}

		private ExternalCommandData commandData;

		private bool IsPlan = true;

		private DimEquipmentData equipmentData;

		private Document doc;

		private CommonFont fontSetting;
	}
}
